<?php
use Illuminate\Support\Str;
use App\Models\Sms;
use Carbon\Carbon;


/**
 * 接口分页计算
 *
 * @author cqd
 * @param int $page 当前页
 * @param int $per_page 每页数
 * @return array
 */
function offsetPage($page, int $per_page)
{
    $offset = $page - 1;

    $skip = $per_page * $offset;

    return $skip;
}

/**
 * 发送短信
 *
 * @author cqd
 * @param int $phone 手机号
 * @param string $msg 自定义信息
 * @return boolean
 */
function sendCodeAndSave($phone, string $custom_message = null)
{
    $time = time() - 120;
    $date_time = date('Y-m-d H:i:s', $time);
    $myCount = Sms::where('phone', $phone)->where('created_at', '>', $date_time)->count();
    if ($myCount > 5) {
        return [
            'success' => false,
            'message' => '发送短信次数过于频繁',
        ];
    }
    $phoneCount = Sms::where('phone', $phone)->where('created_at', '>', Carbon::now()->subHours(1))->count();
    if ($phoneCount > 30) {
        return [
            'success' => false,
            'message' => '发送短信次数超过限制',
        ];
    }

    $url = 'http://39.107.242.113:7862/sms';
    $ch = curl_init($url);
    $code = mt_rand(100000, 999999);
    $predefined_message = "【第一课堂】验证码为{$code}，提示您保管好自己的验证码，请勿泄露!";
    $expire_time = time() + 300;//五分钟内有效
    $content = !isset($custom_message) ? $predefined_message : $custom_message;
    $post_data = array(
        'account' => env('SMS_USERNAME'),
        'password' => env('SMS_PASSWORD'),
        'content' => $content,
        'mobile' => $phone,
        'extno' => env('SMS_EXTNO'),
        'rt' => 'json',
    );

    $action = 'send';

    $str = 'action=' . $action;

    foreach ($post_data as $k => $v) {
        $str .= '&' . $k . '=' . urlencode($v);
    }
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $str);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
        'Content-Type: application/x-www-form-urlencode; charset=j',
        'Content-Length: ' . strlen($str))
    );

    $recive = curl_exec($ch);
    curl_close($ch);
    $sms_model = new \App\Models\Sms();
    $sms_model->phone = $phone;
    $sms_model->code = $code;
    $sms_model->expire_time = $expire_time;
    $sms_model->content = $content;
    $sms_model->status = 0;
    $sms_model->save();
    $res = json_decode($recive, true);
    if ($res['status'] == 0) {
        $return['message'] = '发送成功';
        $return['success'] = true;
        return $return;
    } else {
        $return['message'] = '发送失败';
        $return['success'] = false;
        return $return;
    }
}



if (!function_exists('timediff')) {
    /**
     * 计算两个时间戳之间相差的日期
     *
     * @param [int] $begin_time
     * @param [int] $end_time
     * @return void
     * @Description
     * @author wjx
     */
    function timediff($begin_time, $end_time)
    {
        //计算天数
        $timediff = $end_time - $begin_time;
        if ($timediff < 0) {
            return '已结束';
        }
        $days = intval($timediff / 86400);
        //计算小时数
        $remain = $timediff % 86400;
        $hours = intval($remain / 3600);
        //计算分钟数
        $remain = $remain % 3600;
        $mins = intval($remain / 60);
        //计算秒数
        $secs = $remain % 60;
        // $res = array("day" => $days,"hour" => $hours,"min" => $mins,"sec" => $secs);
        $res = array("day" => $days, "hour" => $hours, "min" => $mins, "sec" => $secs);
        return $days . "天" . $hours . "小时" . $mins . "分";
    }
}

if (!function_exists('ArraytoXml')) {
    /**
     * 数组转xml(用于处理微信回调)
     *
     * @param [type] $data
     * @return string
     * @Description
     * @author wjx
     */
    function ArraytoXml($data)
    {
        if (!is_array($data) || count($data) <= 0) {
            throw new InvalidArgumentException('Convert To Xml Error! Invalid Array!');
        }

        $xml = '<xml>';
        foreach ($data as $key => $val) {
            $xml .= is_numeric($val) ? '<' . $key . '>' . $val . '</' . $key . '>' :
            '<' . $key . '><![CDATA[' . $val . ']]></' . $key . '>';
        }
        $xml .= '</xml>';

        return $xml;
    }
}

if (!function_exists('set_order_no')) {
    /**
     * 生成随机订单号
     *
     * @return void
     * @Description
     * @author wjx
     */
    function set_order_no()
    {
        $str = date('Ymdhis') . mt_rand(10000, 99999);
        return $str;
    }
}

if (!function_exists('set_card_no')) {
    /**
     * 生成会员卡卡号
     *
     * @return void
     * @Description
     * @author wjx
     */
    function set_card_no()
    {
        $str = strtoupper(Str::random(16));
        return $str;
    }
}

if (!function_exists('curl_get_contents')) {
    /**
     * 使用curl获取远程数据
     *
     * @param string $url url连接
     *
     * @return string 获取到的数据
     */
    function curl_get_contents($url)
    {
        set_time_limit(0);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url); //设置访问的url地址
        curl_setopt($ch, CURLOPT_TIMEOUT, 5); //设置超时
        curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); //用户访问代理 User-Agent
        curl_setopt($ch, CURLOPT_REFERER, $_SERVER['HTTP_HOST']); //设置 referer
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); //跟踪301
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //返回结果
        $r = curl_exec($ch);
        curl_close($ch);

        return $r;
    }
}

if (!function_exists('arraySort')) {
    /**
     * 数组排序
     *
     * @param [type] $array
     * @param [type] $keys
     * @param string $sort
     * @return void
     * @Description
     * @author wjx
     */
    function arraySort($array, $keys, $sort = 'asc')
    {
        $newArr = $valArr = array();
        foreach ($array as $key => $value) {
            $valArr[$key] = $value[$keys];
        }
        ($sort == 'asc') ? asort($valArr) : arsort($valArr); //先利用keys对数组排序，目的是把目标数组的key排好序
        reset($valArr); //指针指向数组第一个值
        foreach ($valArr as $key => $value) {
            $newArr[$key] = $array[$key];
        }
        return array_column($newArr, null);
        // return $newArr;
    }
}

if (!function_exists('objectToArray')) {
    /**
     * 对象转数组
     *
     * @param [type] $obj
     * @return void
     * @Description
     * @author wjx
     */
    function objectToArray($obj)
    {
        //首先判断是否是对象
        $arr = is_object($obj) ? get_object_vars($obj) : $obj;
        if (is_array($arr)) {
            //这里相当于递归了一下，如果子元素还是对象的话继续向下转换
            return array_map(__FUNCTION__, $arr);
        } else {
            return $arr;
        }
    }
}

function ajax_error($msg = '')
{
    return response()->json([
        'code' => 0,
        'msg' => $msg,
    ]);
}

function ajax_success($msg = '')
{
    return response()->json([
        'code' => 1,
        'msg' => $msg,
    ]);
}

function ajax_data($data = '')
{
    return response()->json([
        'code' => 1,
        'data' => $data,
    ]);
}
